using System;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Net;
using Microsoft.Extensions.Options;
using Book.Blog.Core.DTOs;
using Book.Blog.Core.Interfaces;
using System.Text;
using HandlebarsDotNet;

namespace Book.Blog.Infrastructure.Services
{
    public class EmailService : IEmailService
    {
        private readonly EmailConfigurationDTO _emailConfig;

        public EmailService(IOptions<EmailConfigurationDTO> emailConfig)
        {
            _emailConfig = emailConfig.Value;
        }

        public async Task SendEmailAsync(EmailMessageDTO message)
        {
            using var client = CreateSmtpClient();
            using var mailMessage = new MailMessage
            {
                From = new MailAddress(_emailConfig.FromAddress ?? _emailConfig.Username, _emailConfig.FromName),
                Subject = message.Subject ?? string.Empty,
                Body = message.Body,
                IsBodyHtml = message.IsHtml
            };

            mailMessage.To.Add(message.To);

            if (message.Attachments != null)
            {
                foreach (var attachment in message.Attachments)
                {
                    using var ms = new MemoryStream(attachment.Content);
                    var att = new Attachment(ms, attachment.FileName, attachment.ContentType);
                    mailMessage.Attachments.Add(att);
                }
            }

            await client.SendMailAsync(mailMessage);
        }

        public async Task SendEmailWithTemplateAsync(string to, string templateName, object model)
        {
            var template = await LoadTemplateAsync(templateName);
            var handlebars = Handlebars.Create();
            var compiledTemplate = handlebars.Compile(template);
            var body = compiledTemplate(model);

            var message = new EmailMessageDTO
            {
                To = to,
                Body = body,
                IsHtml = true
            };

            await SendEmailAsync(message);
        }

        private SmtpClient CreateSmtpClient()
        {
            return new SmtpClient(_emailConfig.SmtpServer)
            {
                Port = _emailConfig.Port,
                Credentials = new NetworkCredential(_emailConfig.Username, _emailConfig.Password),
                EnableSsl = _emailConfig.EnableSsl
            };
        }

        private async Task<string> LoadTemplateAsync(string templateName)
        {
            var templatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "EmailTemplates", $"{templateName}.html");
            if (!File.Exists(templatePath))
            {
                throw new FileNotFoundException($"Email template {templateName} not found");
            }
            return await File.ReadAllTextAsync(templatePath);
        }
    }
} 